package com.pentofab.payrollmanagement.ui.controller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;

import com.pentofab.payrollmanagement.application.PayrollApplicationFactory;
import com.pentofab.payrollmanagement.dao.EmployeeDao;
import com.pentofab.payrollmanagement.dao.model.Company;
import com.pentofab.payrollmanagement.dao.model.Department;
import com.pentofab.payrollmanagement.dao.model.EmpCategory;
import com.pentofab.payrollmanagement.dao.model.Units;
import com.pentofab.payrollmanagement.dao.model.UserAccounts;

public class CompanyCategoriesTabController extends AbstractUIController {

	@FXML
	Parent root;
	@FXML
	private ListView<EmpCategory> employeeCategoriesList;

	private Company company;
	private UserAccounts userAccounts;
	@FXML
	TextField importFileLoc;
	@FXML
	TextField exportFileLoc;
	@FXML
	TextField idList;
	private EmployeeDao employeeDao =  PayrollApplicationFactory.getEmployeeMgmt();
	@Override
	public Parent getView() {
		return root;
	}

	@Override
	public String getTitle() {

		return null;
	}

	@Override
	public void refreshUI(Object... args) {
		
		importFileLoc.clear();
		exportFileLoc.clear();
		idList.clear();
		
		
		if (args != null && args.length > 0) {
			Company company = (Company) args[0];
			this.company = company;
			if(args.length > 1 && args[1] instanceof UserAccounts){
				userAccounts = (UserAccounts) args[1];
			}
		}

		EmployeeDao empDao = PayrollApplicationFactory.getEmployeeMgmt();
		try {
			List<EmpCategory> employeeCategories = empDao
					.getAllEmpCategory(this.company.getCompanyID());
			ObservableList<EmpCategory> empCategoriesList = FXCollections
					.observableArrayList();
			if(employeeCategories != null)
			empCategoriesList.addAll(employeeCategories);
			this.employeeCategoriesList.setItems(empCategoriesList);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void add() {
		PayrollApplicationFactory.getMainController()
				.showScreen(MainController.ADD_EMPLOYEE_CATEGORY_SCREEN, true,
						this.company);
	}

	public void edit() {
		EmpCategory category = this.employeeCategoriesList.getSelectionModel()
				.getSelectedItem();
		if (category != null) {
			PayrollApplicationFactory.getMainController().showScreen(
					MainController.ADD_EMPLOYEE_CATEGORY_SCREEN, true,
					this.company, category);
		} else {
			showError("Select a category to edit");
		}
	}
	
	public void goBack() {

		PayrollApplicationFactory.getMainController().showScreen(
				MainController.COMPANIES_LIST_SCREEN, false, userAccounts);
	}

	public void deleteCategory() {

	}
	
	public void browseImport(){

		try{
			FileChooser fileChooser = new FileChooser(); 
			fileChooser.setTitle("Select Category File");

			File file = fileChooser.showOpenDialog(null);
			File destinationFile = new File(file.getAbsolutePath());
			String fileName = destinationFile.getName();
			if(file!=null && !file.isDirectory()){

				importFileLoc.setText(destinationFile.getAbsolutePath());
				if(fileName !=null && !fileName.equals(UIMessages.FileName.CATEG_LIST)){
					showError("To import Employee category, Please select file having name  :"+UIMessages.FileName.CATEG_LIST);
					refreshUI();
					return;
				}


				FileReader fr = new FileReader(file);

				BufferedReader br = new BufferedReader(fr);

				String colnms = br.readLine();
				if(colnms == null || colnms.equals("")){

					showError("No data in file : "+fileName);
					refreshUI();
					br.close();
					return;
				}


				String[] colArray = colnms.split(",");
				if(colArray == null || colArray.length != 3	){

					showError("Improper data in file : "+fileName+", Valid data must contain only \n"
							+ "Code,Description,Comp Code");
					br.close();
					refreshUI();
					return;
				}
				br.close();

			}else{
				showInfo("Export Operation cancelled as file not selected for import.");
				refreshUI();
				return;
			}

		}catch(Exception e){
			refreshUI();
			showError("Error while importing Department data.");
		}
	}

	public void importSubmit(){

		try{

			File file = new File(importFileLoc.getText().trim());
			ArrayList<HashMap<String, String>> deptInfoMap = new ArrayList<HashMap<String,String>>();
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			String[] clnmsArray = br.readLine().split(",");
			String dataLine = null;
			while((dataLine = br.readLine()) != null){
				
				System.out.println("dataLine : "+dataLine);
				String[] data = dataLine.split(",");

				HashMap<String, String> cur = new HashMap<String, String>();
				for(int i= 0;i < data.length;i++){

					cur.put(clnmsArray[i],data[i].replaceAll("'", ""));
				}
				deptInfoMap.add(cur);

			}

			System.out.println("category : "+deptInfoMap.size());
			Iterator<HashMap<String, String>> companyInfoMapIterator = deptInfoMap.iterator();
			StringBuffer errorBuffer = new StringBuffer();
			while(companyInfoMapIterator.hasNext()){

				HashMap<String, String > current = companyInfoMapIterator.next();
				try{
					EmpCategory cat = new EmpCategory();
					
					cat.setCode(current.get("Code"));
					cat.setDescription(current.get("Description"));
					cat.setCompanyCode(current.get("Comp Code"));
					employeeDao.addEmpCategory(cat);
				}catch(Exception e){
					e.printStackTrace();
					errorBuffer.append("Code : "+current.get("Code")+", Description : "+current.get("Description")+", Comp Code : "+current.get("Comp Code")+"\n");
				}
			}

			if(!errorBuffer.toString().equals("")){
				
				showError("Failed to add following Employee Caegory due to data error,\n 1. Department with code may already exists\n"
						+ "2. Parent Company may not be present.\n"+errorBuffer);
			}

			refreshUI();
			br.close();
		}catch(Exception e){
			e.printStackTrace();
			refreshUI();
			showError("Error while importing company data.");
		}

		showInfo("Successfuly imported employee categors");
	}

	public void browseExport(){


		if(idList.getText().trim().equals("")){

			showError("Please enter codes seprated by',' to export.");
			return;
		}

		try{
			DirectoryChooser fileChooser = new DirectoryChooser(); 
			fileChooser.setTitle("Select Destination");

			File file = fileChooser.showDialog(null);
			File destinationFile = new File(file.getAbsolutePath());
			if(file!=null && file.isDirectory()){

				exportFileLoc.setText(destinationFile.getAbsolutePath());

			}else{
				showInfo("Export Operation cancelled as Directory not selected for export.");
				refreshUI();
				return;
			}

		}catch(Exception e){
			refreshUI();
			showError("Error while exporting Department data.");
		}

	}
	public void exportSubmit(){
		try{

			if(idList.getText().trim().equals("")){

				showError("Please select Department codes seprated by',' to export.");
				return;
			}

			String selectedCodes = idList.getText().trim();
			String[] codesArray = selectedCodes.split(",");
			File file = new File(exportFileLoc.getText()+"//"+UIMessages.FileName.CATEG_LIST);
			FileWriter fw =new FileWriter(file,true);
			BufferedWriter bw =new BufferedWriter(fw);
			bw.write("Code,Description,Comp Code\n");

			for(int i=0; i < codesArray.length;i++){

				EmpCategory cat = employeeDao.getEmpCategory(company.getCompanyID(), codesArray[i]);
				StringBuffer dataLine = new StringBuffer();
				dataLine.append(cat.getCode()).append(",");
				dataLine.append(cat.getDescription()).append(",");
				dataLine.append(cat.getCompanyCode());
				bw.write(dataLine.toString()+"\n");
			}

			showInfo("Successfuly exported category.");
			bw.flush();
			fw.flush();
			bw.close();fw.close();
		}catch(Exception e){
			e.printStackTrace();
			showError("Error while exporting Employee category data.");
		}
	}
}
